package com.mj.listen3.链表;

/**
 *
 */
public class _0_在单链表中删除倒数第K个节点 {
    public ListNode removeLastKthNode2(ListNode head, int lastKth) {
        if (head == null || lastKth < 1) return head;
        ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            lastKth--;
        }

        if (lastKth == 0) {
            // 删除的是头节点
            head = head.next;
        }

        if (lastKth < 0) {
            // 说明k的值没有超出链表的长度，找出要删除节点的前一个节点
            cur = head;
            while (++lastKth != 0) {
                cur = cur.next;
            }
            // lastKth == 0
            cur.next = cur.next.next;
        }

        // lastKth > 0 不用管，因为此时说明k的值超出链表的长度

        return head;
    }
}
